<template>
  <div class="input-select-dialog">
    <el-input
      ref="selectInputRef"
      :placeholder="placeholder"
      v-model.trim="inputValue"
      :clearable="true"
      size="small"
      v-bind="$attrs"
      :disabled="allDisabled"
      @clear="clearInput"
      @keyup.enter="handleSearchInput"
    >
      <template #append>
        <el-button :icon="Search" @click.stop.prevent="handleSearchInput" :disabled="allDisabled" size="small" />
      </template>
    </el-input>
    <CustomDialog
      class="vxe-table--ignore-clear my-custom-dialog"
      ref="dialogRef"
      append-to-body
      :dialogConfig="dialogConfig"
      fullscreen
      :dialogHeight="'95vh'"
      destroy-on-close
      @close-dialog="handleCloseDialog"
    >
      <div ref="dialogContentRef" class="dialog-content" style="height: 100%">
        <CustomForm
          ref="formRef"
          class="search-form"
          :form-data="formDataValue"
          :submit-event="submitEvent"
          :form-items="formItemsValue"
          :reset-event="resetEvent"
        />
        <CustomElTable
          id="cusom-table"
          class="my-table"
          :height="tableHeight"
          :config="tableConfig"
          :is-show-pager="tableData.length > 0"
          :data="tableData"
          @sort-change="sortChange"
          @row-click="handleRowClick"
          @page-change="handleCurrentChange"
        >
        </CustomElTable>
      </div>
    </CustomDialog>
  </div>
</template>

<script setup>
import { debounce } from 'lodash-es'
import { Search } from '@element-plus/icons-vue'
import { getCommonSelectDataAPI } from '@/api/common'
import CustomDialog from '@/components/CustomDialog/index.vue'
import CustomForm from '@/components/CustomForm/index.vue'
import CustomElTable from '@/components/CustomElTable/index.vue'

defineOptions({
  name: 'InputsSelectDialog'
})
// Props
const props = defineProps({
  // 输入框值
  modelValue: {
    type: [String, Number],
    default: ''
  },
  // 输入框绑定对应code
  bindValue: {
    type: [String, Number],
    default: ''
  },
  //提示
  placeholder: {
    type: String,
    default: ''
  },
  //标题
  dialogTitle: {
    type: String,
    default: 'Dialog'
  },
  // 是否禁用
  allDisabled: {
    type: Boolean,
    default: false
  },
  //表单搜索项
  formItems: {
    type: Array,
    default: () => []
  },
  // 表单绑定值
  formValue: {
    type: Object,
    required: true
  },
  //是否显示搜索按钮
  showSearchButtons: {
    type: Boolean,
    default: true
  },
  //表格列
  tableColumns: {
    type: Array,
    default: () => []
  },
  //自定义请求api
  requestUrl: {
    type: Function,
    default: null
  },
  // 自定义请求参数
  myCustomConfig: {
    type: Object,
    default: () => ({
      //用于输入框绑定对应的值
      codeKey: '',
      //用于输入框绑定对应的值拼接展示 ,
      codeKey2: '',
      //请求数据类型
      type: '',
      //用于搜索指定某类的key 例：customerId
      idName: '',
      //用于搜索指定某类的value 例：34343434
      idValue: '',
      //区分不同模组类型
      gstCodeType: '',
      //customer指定key 0:so,1:si,2:sq,3:sdn
      customerKey: '',
      //指定搜索的key 默认为code_like
      searchKey: ''
    })
  }
})

// Emits
const emit = defineEmits(['selectRowClick', 'selectEnter', 'update:bindValue', 'update:modelValue', 'update:formValue'])

// Local states
const dialogRef = ref(null)
const searchValue = ref('')
const tableHeight = ref(500)
const formRef = ref(null)
const selectInputRef = ref(null)
const dialogContentRef = ref(null)

const formItemsValue = ref(props.formItems)
const tableData = ref([])
const tableConfig = reactive({
  column: [],
  paginationData: {
    pageSize: 50,
    currentPage: 1,
    total: 0
  }
})
const dialogConfig = {
  dialogTitle: props.dialogTitle,
  isShowFooter: false
}
/** 计算表格高度 */
const getTableHeight = debounce(() => {
  nextTick().then(() => {
    const dialogH = dialogContentRef.value?.offsetHeight
    const searchFormH = document.querySelector('.search-form')?.offsetHeight
    tableHeight.value = dialogH - searchFormH - 70
  })
}, 200)

onBeforeUnmount(() => {
  window.removeEventListener('resize', getTableHeight)
})

// const inputValue = ref(props.modelValue)
// const bindCodeValue = ref(props.bindValue)
// const formDataValue = ref(props.formValue)
// Watchers
// watch(inputValue, newValue => {
//   emit('update:modelValue', newValue)
// })
// watch(bindCodeValue, newValue => {
//   emit('update:bindValue', newValue)
// })
// watch(formDataValue, newValue => {
//   emit('update:formValue', newValue)
// })

//computed
const inputValue = computed({
  get() {
    return props.modelValue
  },
  set(newValue) {
    emit('update:modelValue', newValue)
  }
})
const bindCodeValue = computed({
  get() {
    return props.bindValue
  },
  set(newValue) {
    emit('update:bindValue', newValue)
  }
})
const formDataValue = computed({
  get() {
    return props.formValue
  },
  set(newValue) {
    emit('update:formValue', newValue)
  }
})

// Methods
/**聚焦输入框 */
const focusInput = () => {
  nextTick(() => {
    selectInputRef.value?.focus()
  })
}
/**清空输入框 */
const clearInput = () => {
  resetInput()
}
/**重置输入框 */
const resetInput = () => {
  inputValue.value = ''
  bindCodeValue.value = ''
}
/**表格行点击 */
const handleRowClick = row => {
  emit('selectRowClick', row)
}
/**根据tableData生成列 */
const generateTableColumns = data => {
  const columns = []
  if (!tableData.value.length) return
  if (!props.tableColumns.length) {
    const firstItem = data[0]
    for (const key in firstItem) {
      if (Object.prototype.hasOwnProperty.call(firstItem, key)) {
        if (key === 'Cid') {
          columns.unshift({
            label: key,
            prop: key,
            type: 'normal',
            sortable: key === 'Stock_Level' ? 'custom' : false
          })
        } else {
          columns.push({
            label: key,
            prop: key,
            type: 'normal',
            sortable: key === 'Stock_Level' ? 'custom' : false
          })
        }
      }
    }
    tableConfig.column = columns
  } else {
    tableConfig.column = props.tableColumns
  }
}
/**分页切换 */
const handleCurrentChange = currentPage => {
  tableConfig.paginationData.currentPage = currentPage
  handleFetchData()
}
/**input输入框搜索 */
const handleSearchInput = () => {
  searchValue.value = 'enter'
  handleFetchData()
}
/**弹窗表单搜索 */
const submitEvent = () => {
  tableConfig.paginationData.currentPage = 1
  searchValue.value = 'search'
  handleFetchData()
}
/**弹窗表单搜索重置 */
const resetEvent = () => {
  formDataValue.value = {}
  tableConfig.paginationData.currentPage = 1
  searchValue.value = ''
  handleFetchData()
}
/**关闭弹窗 */
const handleCloseDialog = () => {
  tableConfig.paginationData.currentPage = 1
  formDataValue.value = {}
  searchValue.value = ''
  dialogRef.value.closeDialog()
}
/**表单自定义排序 */
const sortChange = column => {
  if (column.order) {
    formDataValue.value.ud = column.order === 'descending' ? 'DESC' : 'ASC'
    formDataValue.value.sf = column.prop
  } else {
    formDataValue.value.ud = ''
    formDataValue.value.sf = ''
  }
  searchValue.value = 'search'
  handleFetchData()
}
/**根据不同key生成 */
const generateDisplayValue = row => {
  const value1 = row[props.myCustomConfig.codeKey]
  const value2 = row[props.myCustomConfig.codeKey2] || ''
  return value2 ? `${value1},${value2}` : value1
}

/**获取数据 */
const handleFetchData = async () => {
  let requestData = {
    detail: false,
    page_size: tableConfig.paginationData.pageSize,
    page_no: tableConfig.paginationData.currentPage,
    all: false,
    type: props.myCustomConfig.type,
    customer_key: props.myCustomConfig.customerKey,
    ext_req: {
      gst_code_type: props.myCustomConfig.gstCodeType,
      ...(props.myCustomConfig.idName ? { [props.myCustomConfig.idName]: props.myCustomConfig.idValue } : {})
    }
  }
  if (searchValue.value === 'enter') {
    if (props.myCustomConfig.searchKey) {
      requestData[props.myCustomConfig.searchKey] = inputValue.value
    } else {
      requestData.code_like = inputValue.value
    }
  } else if (searchValue.value === 'search') {
    requestData = {
      ...requestData,
      ...formDataValue.value
    }
  }
  const apiFunction = props.requestUrl || getCommonSelectDataAPI
  try {
    const response = await apiFunction(requestData)
    tableData.value = response.data.list
    tableConfig.paginationData.total = response.data.total
    generateTableColumns(response.data.list)
    if (searchValue.value === 'enter' && response.data.list.length === 1) {
      inputValue.value = generateDisplayValue(response.data.list[0])
      bindCodeValue.value = response.data.list[0].Cid
      emit('selectEnter', inputValue.value, response.data.list[0])
      dialogRef.value.closeDialog()
    } else {
      dialogRef.value.openDialog()
      getTableHeight()
    }
  } catch (error) {
    console.error(error)
  }
}

defineExpose({
  focusInput,
  dialogRef,
  handleCloseDialog
})
</script>

<style lang="scss" scoped>
:deep(.el-table th.el-table__cell > .cell) {
  display: inline-block;
  box-sizing: border-box;
  position: relative;
  vertical-align: middle;
  padding-left: 10px;
  padding-right: 10px;
  width: 100%;
  white-space: nowrap !important;
}
</style>
